import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:lib_common/lib_common.dart';
import 'package:package_info_plus/package_info_plus.dart';

class AppManager {
  /// 应用原生通信通道
  late BasicMessageChannel _appMessageChannel;

  AppManager._() {
    _appMessageChannel = const BasicMessageChannel(NativeConstants.appChannelName, JSONMessageCodec());
  }

  // 单例实例
  static final AppManager _instance = AppManager._();

  // 工厂构造函数
  factory AppManager.getInstance() {
    return _instance;
  }

  /// 全局context
  final globalKey = GlobalKey<NavigatorState>();

  get context => globalKey.currentContext;

  /// app运行渠道
  String _runtimeChannel = "";

  /// android系统版本
  int _androidSystemVersion = 1;

  /// 实名配置
  AppConfig? _authenticationConfig;

  String? currentRoute = RoutePaths.splash;
  String? previousRoute = "";

  String getAppId() {
    return "__UNI__973E939";
  }

  /// 获取当前运行渠道
  Future<String> getRuntimeChannel() async {
    if (_runtimeChannel.isNotEmpty) {
      // 已获取过，直接返回
      LogUtils.v('channel in memory:$_runtimeChannel');
      return _runtimeChannel;
    }

    String runtimeChannel = "";
    if (kReleaseMode) {
      // 获取本地缓存渠道数据
      runtimeChannel = SpUtil.getString(CacheConstants.appChannel, defValue: "") ?? "";
    }

    if (runtimeChannel.isNotEmpty) {
      // 本地已缓存渠道
      LogUtils.v('channel in cache:$runtimeChannel');
      _runtimeChannel = runtimeChannel;
    } else if (Platform.isAndroid) {
      // 尝试获取平台渠道
      var channel = await _appMessageChannel.send({NativeConstants.method: NativeConstants.runtimeChannel});
      if (channel is String) {
        LogUtils.v('channel in native:$channel');
        _runtimeChannel = channel;
        if (kReleaseMode) {
          // 调试模式不记录渠道到本地
          await SpUtil.putString(CacheConstants.appChannel, channel);
        }
      } else {
        LogUtils.e('channel error:$channel');
        _runtimeChannel = Platform.operatingSystem;
      }
    } else {
      _runtimeChannel = Platform.operatingSystem;
      LogUtils.v('channel in native:$_runtimeChannel');
      await SpUtil.putString(CacheConstants.appChannel, _runtimeChannel);
    }
    return _runtimeChannel;
  }

  /// 获取当前设备安卓系统版本
  Future<int> getAndroidSystemVersion() async {
    if (_androidSystemVersion > 1) {
      // 已获取过，直接返回
      LogUtils.v('androidVersion in memory:$_androidSystemVersion');
      return _androidSystemVersion;
    }
    if (Platform.isAndroid) {
      var versionResult = await _appMessageChannel.send({NativeConstants.method: NativeConstants.androidSystemVersion});
      if (versionResult is int) {
        LogUtils.v('androidVersion in native:$versionResult');
        _androidSystemVersion = versionResult;
      } else {
        LogUtils.e('androidVersion error:$versionResult');
      }
    } else {
      LogUtils.e('androidVersion error:Not Android System');
    }
    return _androidSystemVersion;
  }

  /// 初始化原生sdk
  Future<bool> initNativeSDK() async {
    var result = await _appMessageChannel.send({NativeConstants.method: NativeConstants.initNativeSDK});
    if (result == true) {
      return result;
    } else {
      LogUtils.e("initNativeSDK error:$result");
      return false;
    }
  }

  Future<String> getAppVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String versionName = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    return "$versionName-$buildNumber";
  }

  void setAppConfig(AppConfig appConfig) {
    _authenticationConfig = appConfig;
  }

  /// 是否需要实名认证
  bool needAuthentication() {
    if (_authenticationConfig == null) {
      LogUtils.v("needAuthentication: config is Null");
      return false;
    }
    if (!(_authenticationConfig?.enable ?? false)) {
      LogUtils.v("needAuthentication: config not enable");
      return false;
    }
    if (!(_authenticationConfig?.channel?.contains(_runtimeChannel) ?? false)) {
      LogUtils.v("needAuthentication: not auth channel");
      return false;
    }
    var userLevel = UserManager.getInstance().getUserLevel();
    var allowEnterLevel = _authenticationConfig?.allowEnterLevel ?? "1";
    if (int.parse(userLevel) >= int.parse(allowEnterLevel)) {
      return false;
    }
    // var delayTime = int.parse(_authenticationConfig?.delayTime ?? "1") ;
    return true;
  }
}
